package com.illtamer.infinite.morii.util;

import org.springframework.lang.NonNull;

public class CommonUtil {

    public static int count(String s, char c) {
        int i = 0;
        for (char c1 : s.toCharArray()) if (c == c1) ++i;
        return i;
    }

    /**
     * @return [subName, suffix]
     */
    @NonNull
    public static String[] splitSuffix(@NonNull String s) {
        String[] result = new String[2];
        StringBuilder builder = new StringBuilder();
        boolean find = false;
        char c;
        for (int i = s.length()-1; i >= 0; -- i) {
            c = s.charAt(i);
            if (c == '.' && !find) {
                result[1] = builder.toString();
                builder.setLength(0);
                find = true;
                continue;
            }
            builder.insert(0, c);
        }
        result[0] = builder.toString();
        if (result[1] == null) result[1] = "";
        return result;
    }

    /**
     * 切分uri
     * @param deep 切分的深度 3or4
     * @return [groupId, artifactId, version(, name)]
     * */
    public static String[] splitKey(String key, int deep) {
        String[] splits = new String[deep];
        StringBuilder builder = new StringBuilder();
        char splitChar = '/';
        int index = deep-1;
        char[] chars = key.toCharArray();
        for (int i = chars.length-1; i >= 0; -- i) {
            if (chars[i] == splitChar && index != 0) {
                splits[index --] = builder.toString();
                builder.setLength(0);
                -- i;
            }
            builder.insert(0, chars[i]);
        }
        splits[index] = builder.toString();
        while (index != 0) splits[-- index] = "";
        return splits;
    }

    public static boolean isNull(Object... objects) {
        for (Object object : objects)
            if (object == null) return true;
        return false;
    }

}
